package org.exteen.tag.core;

import org.exteen.ExteenException;
import org.exteen.exec.ExteenContext;
import org.exteen.exec.Tag;
import org.exteen.output.ExteenStream;
import org.exteen.parser.Node;

public class NewTag extends Tag {

    public void doTag(ExteenContext ctx, ExteenStream stream) {

        Node node = ctx.getNode();
        String varName = ctx.getVarAttrValue("var");
        if (varName==null) {
            throw new ExteenException("Required attribute 'var' missing");
        }

        boolean override = ctx.parseAttributeAsBoolean("override", true);

        Object clazz = node.getAttributeValue("class", ctx);
        if (clazz==null || clazz.toString().trim().length()==0) {
            throw new ExteenException("Required attribute 'class' missing");
        }
        String className = clazz.toString().trim();
        if (node.getChildren().size()>0) {
            throw new ExteenException("Tag new may not have body");
        }

        try {
            Object value = Class.forName(className).newInstance();
            ctx.getParent().set(varName, value, override);
        } catch (Exception e) {
            throw new ExteenException("Could not instantiate class " + clazz, e);
        }
    }
}